package org.spiderflow.common.concurrent;

import org.spiderflow.common.model.SpiderNode;

import java.util.Comparator;
import java.util.Objects;
import java.util.PriorityQueue;

/**
 * @author zsh
 */
public class ParentPriorThreadSubmitStrategy implements ThreadSubmitStrategy {
    private static final String STRATEGY_TAG = "parent";

    public static boolean isMatch(String strategy) {
        return STRATEGY_TAG.equalsIgnoreCase(strategy);
    }

    private final Object mutex = this;

    private static final Comparator<SpiderNode> COMPARATOR = (o1, o2) -> {
        if (Objects.equals(o1.getNodeId(), o2.getNodeId())) {
            return 0;
        } else if (o1.hasLeftNode(o2.getNodeId())) {
            return 1;
        } else {
            return -1;
        }
    };

    private final PriorityQueue<SpiderFutureTask<?>> priorityQueue =
            new PriorityQueue<>((o1, o2) -> COMPARATOR.compare(o1.getNode(), o2.getNode()));

    @Override
    public Comparator<SpiderNode> comparator() {
        return COMPARATOR;
    }

    @Override
    public void add(SpiderFutureTask<?> task) {
        synchronized (mutex) {
            priorityQueue.add(task);
        }
    }

    @Override
    public boolean isEmpty() {
        synchronized (mutex) {
            return priorityQueue.isEmpty();
        }
    }

    @Override
    public SpiderFutureTask<?> get() {
        synchronized (mutex) {
            return priorityQueue.poll();
        }
    }

}
